Ext.namespace('VAS');
/**
 * 审核步骤表格窗口
 * @param {} $config
 */

VAS.AuditStepsGrid = function($config) {
	var _this = this;
	this.config = $config;
	VAS.AuditStepsGrid.superclass.constructor.call(this, $config);
};

//function createGridButton(value, contentid, record) {
////	new Ext.form.CompositeField({  items: [
////                            {xtype: 'displayfield', value: value}
////                           , {xtype: 'button',    text: 'select', handler : function(btn, e) {
////            var win =new VAS.AuditSelectWindow();
////				win.show();
////        }}
////        ]}).render(document.body, contentid);
//
//        new Ext.Button({text: 'select',
//        		handler : function(btn, e) {
//            var win =new VAS.AuditSelectWindow();
//				win.show();
//        }}).render(document.body, contentid);	
//    }

Ext.extend(VAS.AuditStepsGrid,Ext.grid.GridPanel,{
	id:'stepGrid',
	initComponent : function() {
		var _this=this;		
		
		_this._getHeight = function(_height,_y) {
			if (typeof(_height) !== "undefined") {
				if (typeof(_height)==='string'&&_height.indexOf('%') > -1) {
					$height = document.body.clientHeight -_y-307;			
				} else if(typeof(_height)==='number'){
					$height = _height - 50;
				}
			} 
			return $height;
		}
		
		_this.cellActions = new Ext.ux.grid.CellActions({
			listeners:{
				action:function(grid, record, action, value) {
//					Ext.ux.Toast.msg('Event: action', 'You have clicked: <b>{0}</b>, action: <b>{1}</b>', value, action);
//					record.set('userName','test');
//					record.commit();
					var win =new VAS.AuditSelectWindow({record:record,
						modal:true
					});
					win.show();
				}
				,beforeaction:function() {
//					Ext.ux.Toast.msg('Event: beforeaction', 'You can cancel the action by returning false from this event handler.');
				}
			}
			,callbacks:{
				'icon-undo':function(grid, record, action, value) {
					Ext.ux.Toast.msg('Callback: icon-undo', 'You have clicked: <b>{0}</b>, action: <b>{1}</b>', value, action);
				}
			}
			,align:'left'
			
		});

		_this.cm  = new Ext.grid.ColumnModel(
			[
		        {
			        header: '审核步骤',
			        width: 200,
			        dataIndex: 'step'
			    },
			    {
			        header: '操作员',
			        resizable: true,
			        width: 300,
			        dataIndex: 'userName'
			      ,cellActions:[{
						 iconCls:'icon_search'					
						,hideMode:'display'
					 }]
			    }
		    ]
		);		
		_this.ds = new Ext.data.Store({
			autoLoad : true,
			url : "admin/audit/auditStep!getStepConfig.action",
			reader : new Ext.data.JsonReader({
				root:'data'
			}, [
				{name: 'step'},
				{name: 'userName'},
				{name: 'userId'}
			])
		});	 	
		var config = {
			
			width: _this.config.width,
			viewConfig : {
				forceFit : true
			}
			,height: _this._getHeight('69%',2)
			,store:_this.ds,
			cm:_this.cm,
			plugins:[_this.cellActions]
		};
		Ext.apply(this, config);
		Ext.apply(this.initialConfig, config);
		VAS.AuditStepsGrid.superclass.initComponent.apply(this, arguments);
	},
	//根据类型得到审核步骤数
	onRender : function(ct, position) {
		var _this=this;
		this.colModel.defaultSortable = true;
		VAS.AuditStepsGrid.superclass.onRender.call(this, ct, position);	
		this.store.on('load', function() {
			
			
			if(this.store.getCount() >0 ){
			Ext.getCmp("stepSelect").setValue(this.store.getCount());
			}else{
				Ext.getCmp("stepSelect").setValue('');
			}
		}, this);
	}
});

VAS.AuditStepsGridWindow = function($config) {
	var _this = this;
	this.config = $config;
	VAS.AuditStepsGridWindow.superclass.constructor.call(_this,$config);
};
Ext.extend(VAS.AuditStepsGridWindow,VAS.BasicWindow,{
	 initComponent : function() {
	 	var _this = this;
 		var grid = new VAS.AuditStepsGrid({
 			height:_this.config.height,

 			gridUrl : "admin/audit/auditStep!listEvent.action",
			storeUrl : "admin/audit/auditStep!listUser.action",
			rowNumberer : true,
			checkboxSelModel : true	
		});
		
		Ext.getCmp("typeSelect").on("select",function(combo,record,index){
			flag = "part";
			Ext.getCmp("stepGrid").store.load({
				params: {
					typeCode : combo.getValue()
				}
			});
		});
		
		Ext.getCmp("stepSelect").on("select",function(combo,record,index){
			flag = "all";
			Ext.getCmp("stepGrid").store.load({
				params:{
					typeCode : Ext.getCmp("typeSelect").getValue(),
					step : combo.getValue()
				}
			})
		});
		//	store.data 转换为json字符串
		function postGridData(storeData){	
			var m = storeData ;
			var jsonData = "[";
			for ( var i = 0, len = m.length; i < len; i++ ){  
			var ss = Ext.util.JSON.encode( m.items[i].data);
			if ( i==0 )
			jsonData = jsonData + ss;
			else
			jsonData = jsonData + "," + ss;
			}
			jsonData = jsonData + "]";
			return jsonData;
		 };
		 //检查是否给每个步骤选择操作员
		function  checkGridData(storeData){	
			var m = storeData ;
			for ( var i = 0, len = m.length; i < len; i++ ){
				if ('' == m.items[i].data.userName){
					var stepNo = i+1 ;
					Ext.Msg.alert('提示','步骤'+ stepNo + '未选择操作员' );
					return false;
				}
			}
			return true;
		 };	 
		 //类型设置默认值
		var settType = Ext.getCmp("typeSelect");
		settType.store.load();
		settType.store.on("load",function(store,records,options){
			if(records.length > 0){
				settType.setValue(records[0].get("typeCode"));
				Ext.getCmp("stepGrid").store.load({
					params: {
						typeCode : records[0].get("typeCode")
					}
				});
			}
		});	
		//计算window的高度
		_this._getWinHeight = function(_height,_y) {
			var $height;
			if (typeof(_height) === "string") {
				if (_height.indexOf('%') > -1) {
					var percent = _height.substring(0, _height.length - 1) / 100;
						$height = document.body.clientHeight -_y-157;	
				} else {
					$height = _height ;
				}
			} 
			return $height;
	
		};
		
		
	 	var thisConfig = {
			title: _this.title
			,autoScroll : true
			,height     :_this._getWinHeight(this.height,this.y)
			,items :	[grid],
			buttonAlign : "center"
			,buttons : [{
				id : 'save',
				text : '保存',
				handler : function() {
					var gridStore = Ext.getCmp("stepGrid").store;
					var storeData = gridStore.data;
					if(!checkGridData(storeData)) return ;
					Ext.Ajax.request({
					   url: 'admin/audit/auditStep!saveStepConfig.action',
					   success : function(response, options) {
					   		//检查session是否过期
						    checkTimeOut(response);
					   		var responseObj = Ext.util.JSON.decode(response.responseText);
					   		if(responseObj.success){
					   			if(responseObj.msg == '' || responseObj.msg == undefined){
									responseObj.msg = '成功';
								}
								Ext.MessageBox.alert('提示', responseObj.msg);
								//设置reload参数后，reload
								lastOptions = gridStore.lastOptions;
								Ext.apply(lastOptions.params, {
								    step: 0		//在action中，step为"0"或null，则查询数据库中的数据
								});
								gridStore.reload(lastOptions);
					   		}else{
					   			alertFailure(responseObj);
					   		}
						},
						failure : function(response, options) {
							Ext.Msg.alert('提示','服务器异常！');
						},
					   headers: {
					       'my-header': 'foo'
					   },
					   params: {
					   		data :postGridData(storeData),
					   		typeCode : Ext.getCmp("typeSelect").getValue()
					   		}
					});
				}
			}]
		};
	 	var _config = this.config || {};	
	 	Ext.apply(this, _config);
		Ext.apply(this, thisConfig);
		Ext.apply(this.initialConfig, _config);
		VAS.AuditStepsGridWindow.superclass.initComponent.apply(this, arguments);
	 }
});

Ext.reg('auditStepsGrid-win',VAS.AuditStepsGridWindow);
